package com.gyz.taxiplus;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.BMapManager;
import com.baidu.mapapi.map.Geometry;
import com.baidu.mapapi.map.Graphic;
import com.baidu.mapapi.map.GraphicsOverlay;
import com.baidu.mapapi.map.LocationData;
import com.baidu.mapapi.map.MapController;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationOverlay;
import com.baidu.mapapi.map.Symbol;
import com.baidu.mapapi.map.Symbol.Color;
import com.baidu.platform.comapi.basestruct.GeoPoint;

import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
import android.widget.Toast;
import android.app.Activity;

public class SearchActivity extends Activity {

	private static final int SHOWSTATEBIG1 = 0;
	private static final int SHOWSTATENULL1 = 1;
	private static final int SHOWSTATEBIG2 = 2;
	private static final int SHOWSTATENULL2 = 3;
	private static final int BIGPOINT = 20;
	private static final int NORMALPOINT = 10;
	private BMapManager mapmanager;
	private MapView mapview;
	private MapController mapcontroller;
	private LocationClient locationclient;
	private SearchLocationListener locationlistener = new SearchLocationListener();
	private boolean lostgps = true;
	private MyLocationOverlay mlo;
	private DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
	private String serverip = "59.78.38.170";
	private String deviceid;
	private GeoPoint current;
	private String taxiid;
	private MenuItem item;
	private DocumentBuilder builder;
	private GraphicsOverlay gpo;
	private int showState = SHOWSTATEBIG1;
	private boolean initial = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		mapmanager = new BMapManager(getApplication());
		mapmanager.init("6EC2C3605D628B25C945B9D56F2F9F4EE7C463A7", null);
		setContentView(R.layout.activity_search);
		try {
			builder = dbf.newDocumentBuilder();
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
			finish();
		}
		locationclient = new LocationClient(getApplicationContext());
		locationclient.registerLocationListener(locationlistener);
		setOption();
		mapview = (MapView) findViewById(R.id.mapview);
		mapview.setBuiltInZoomControls(true);
		mapview.setTraffic(true);
		mlo = new MyLocationOverlay(mapview);
		mapview.getOverlays().add(mlo);
		gpo = new GraphicsOverlay(mapview);
		mapview.getOverlays().add(gpo);
		mapcontroller = mapview.getController();
		locationclient.start();
		locationclient.requestLocation();
		mapcontroller.setZoom(17);
		String did = ((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
				.getDeviceId();
		deviceid = did.substring(did.length() - 6, did.length());
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		super.onOptionsItemSelected(item);
		if (item.getItemId() == R.id.call) {
			item.setEnabled(false);
			this.item = item;
			String[] params = { deviceid,
					Integer.toString(current.getLatitudeE6()),
					Integer.toString(current.getLongitudeE6()) };
			CallTaxi call = new CallTaxi();
			call.execute(params);

		}
		return true;
	}

	@Override
	protected void onPause() {
		mapview.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mapview.onResume();
		super.onResume();
	}

	@Override
	protected void onStop() {
		locationclient.stop();
		mapview.destroy();
		super.onStop();
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		mapview.onSaveInstanceState(outState);
		super.onSaveInstanceState(outState);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState) {
		mapview.onRestoreInstanceState(savedInstanceState);
		super.onRestoreInstanceState(savedInstanceState);
	}

	private void setOption() {
		LocationClientOption option = new LocationClientOption();
		option.setOpenGps(true);
		option.setAddrType("all");
		option.setCoorType("bd09ll");
		option.setServiceName("com.baidu.location.service_v3.3");
		option.setPoiExtraInfo(false);
		option.disableCache(true);
		option.setScanSpan(3 * LocationClientOption.MIN_SCAN_SPAN);
		option.setPriority(LocationClientOption.GpsFirst);
		locationclient.setLocOption(option);
	}

	private class SearchLocationListener implements BDLocationListener {

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location.getLocType() == 61 || location.getLocType() == 161) {
				current = new GeoPoint(WelcomeActivity.geoTransfer(location
						.getLatitude()), WelcomeActivity.geoTransfer(location
						.getLongitude()));
				LocationData ld = new LocationData();
				ld.latitude = location.getLatitude();
				ld.longitude = location.getLongitude();
				if (location.hasRadius()) {
					ld.accuracy = location.getRadius();
				}
				mlo.setData(ld);
				if (initial) {
					mapcontroller.animateTo(current);
					initial = false;
				}
				if (location.getLocType() == 61 && lostgps) {
					lostgps = false;
				}
				GetTaxi get = new GetTaxi();
				String[] params = { deviceid,
						Integer.toString(current.getLatitudeE6()),
						Integer.toString(current.getLongitudeE6()) };
				get.execute(params);
				return;
			}
			if (!lostgps) {
				Toast.makeText(getApplicationContext(), R.string.lostgpsLabel,
						Toast.LENGTH_SHORT).show();
				lostgps = true;
			}
		}

		@Override
		public void onReceivePoi(BDLocation location) {
		}

	}

	private class GetTaxi extends AsyncTask<String, Integer, List<Taxi>> {
		private String surl = "http://" + serverip
				+ ":8080/taxitest/jaxrs/customer/get/";

		@Override
		protected List<Taxi> doInBackground(String... params) {
			List<Taxi> list = new ArrayList<Taxi>();
			surl += params[0];
			surl += "?latitude=";
			surl += params[1];
			surl += "&longitude=";
			surl += params[2];
			try {
				URL url = new URL(surl);
				Document doc = builder.parse(url.openStream());
				Node root = doc.getDocumentElement();
				for (Node node = root.getFirstChild(); node != null; node = node
						.getNextSibling()) {
					String id = node.getAttributes().getNamedItem("primarykey")
							.getNodeValue();
					int latitude = 0, longitude = 0, state = 3;
					for (Node child = node.getFirstChild(); child != null; child = child
							.getNextSibling()) {
						if (child.getNodeName().equals("taxiLatitude")) {
							latitude = Integer.parseInt(child.getTextContent());
						} else if (child.getNodeName().equals("taxiLongitude")) {
							longitude = Integer
									.parseInt(child.getTextContent());
						} else if (child.getNodeName().equals("taxiState")) {
							state = Integer.parseInt(child.getTextContent());
						}
					}
					Taxi taxi = new Taxi(id, latitude, longitude, state);
					list.add(taxi);
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Taxi> result) {
			super.onPostExecute(result);
			gpo.removeAll();
			for (Taxi taxi : result) {
				System.out.println(taxi.getState());
				Symbol symbol = new Symbol();
				Color color = symbol.new Color();
				Geometry gm = new Geometry();
				if (taxi.getId().equals(taxiid)) {
					color.red = 255;
					color.green = 0;
					color.blue = 0;
					switch (showState) {
					case SHOWSTATEBIG1:
					case SHOWSTATEBIG2:
						gm.setPoint(taxi.getPt(), BIGPOINT);
						showState++;
						break;
					case SHOWSTATENULL1:
					case SHOWSTATENULL2:
						showState++;
						continue;
					default:
						gm.setPoint(taxi.getPt(), NORMALPOINT);
						break;
					}
				} else if (taxi.getState() == Taxi.WAITING) {
					color.red = 0;
					color.green = 255;
					color.blue = 0;
					gm.setPoint(taxi.getPt(), NORMALPOINT);
				} else {
					color.red = 128;
					color.green = 128;
					color.blue = 128;
					gm.setPoint(taxi.getPt(), NORMALPOINT);
				}
				color.alpha = 200;
				symbol.setPointSymbol(color);
				Graphic graphic = new Graphic(gm, symbol);
				gpo.setData(graphic);
			}
			mapview.refresh();
		}

	}

	private class CallTaxi extends AsyncTask<String, Integer, String> {
		private String surl = "http://" + serverip
				+ ":8080/taxitest/jaxrs/customer/call/";

		@Override
		protected String doInBackground(String... params) {
			surl += params[0];
			surl += "?latitude=";
			surl += params[1];
			surl += "&longitude=";
			surl += params[2];
			try {
				URL url = new URL(surl);
				Document doc = builder.parse(url.openStream());
				Node root = doc.getDocumentElement();
				return root.getAttributes().getNamedItem("primarykey")
						.getNodeValue();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (SAXException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String tid) {
			if (null == tid) {
				Toast.makeText(getApplicationContext(),
						R.string.failFindingTaxi, Toast.LENGTH_SHORT).show();
				item.setEnabled(true);
			} else {
				System.out.println(tid);
			}
			taxiid = tid;
		}

	}

}